import React, { ReactElement, useEffect } from 'react';
import { DeviceEventEmitter } from 'react-native';

import Provider from './reducer';
import styles from './style';
import Notch, { NotchType } from '../../components/Notch';
import Container from './components/Container';

import {
  updateList,
  updateCapacity,
  updateCurrentDownload,
  setNetSpeed,
  setSelectedPIds,
  setSelectedAllDownloading
} from './actions';
import netSpeed from '../../util/native/netSpeed';
import {
  DOWNLOAD_VIDEO_TASK_SUCCESS,
  DOWNLOAD_VIDEO_TASK_PROGRESS,
  DOWNLOAD_VIDEO_TASK_DELETE,
  DOWNLOAD_VIDEO_TASK_START,
  DOWNLOAD_VIDEO_TASK_PAUSE,
  DOWNLOAD_VIDEO_TASK_FAIL
} from '../../util/videoDownload/constant';

export default (): ReactElement => {
  useEffect((): (() => void) => {
    updateList();
    updateCapacity();
    updateCurrentDownload();
    setSelectedPIds([]);
    setSelectedAllDownloading(false);

    let latestBytes = netSpeed.getTotalRxBytes();

    setTimeout((): void => {
      const currentBytes = netSpeed.getTotalRxBytes();
      setNetSpeed((currentBytes - latestBytes) / 0.1);
      latestBytes = currentBytes;
    }, 100);

    const timer = setInterval((): void => {
      const currentBytes = netSpeed.getTotalRxBytes();
      setNetSpeed((currentBytes - latestBytes) / 1);
      latestBytes = currentBytes;
    }, 1000);

    const successSubscription = DeviceEventEmitter.addListener(
      DOWNLOAD_VIDEO_TASK_SUCCESS,
      (): void => {
        updateList();
        setTimeout((): void => {
          updateCurrentDownload();
        }, 500);
        updateCapacity();
      }
    );

    const progressSubscription = DeviceEventEmitter.addListener(
      DOWNLOAD_VIDEO_TASK_PROGRESS,
      (): void => {
        updateCurrentDownload();
      }
    );

    const deleteSubscription = DeviceEventEmitter.addListener(
      DOWNLOAD_VIDEO_TASK_DELETE,
      (): void => {}
    );

    const startSubscription = DeviceEventEmitter.addListener(
      DOWNLOAD_VIDEO_TASK_START,
      (): void => {
        updateList();
        updateCurrentDownload();
      }
    );

    const pauseSubscription = DeviceEventEmitter.addListener(
      DOWNLOAD_VIDEO_TASK_PAUSE,
      (): void => {
        updateList();
        updateCurrentDownload();
      }
    );

    const failSubscription = DeviceEventEmitter.addListener(
      DOWNLOAD_VIDEO_TASK_FAIL,
      (): void => {
        updateList();
        updateCurrentDownload();
      }
    );

    return (): void => {
      clearInterval(timer);
      successSubscription.remove();
      progressSubscription.remove();
      deleteSubscription.remove();
      startSubscription.remove();
      pauseSubscription.remove();
      failSubscription.remove();
    };
  }, []);

  return (
    <Provider>
      <Notch style={styles.container} type={NotchType.Top}>
        <Container />
      </Notch>
    </Provider>
  );
};
